// ====================================================
//
// This file is part of the CSCEC81 Cloud Platform.
//
// Create by CSCEC81 Technology <support@cscec81.com>
// Copyright (c) 2020-2021 cscec81.com
//
// ====================================================

package com.cscec81.passport.base.commons.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptUtils {

  private static Cipher cipher;

  private EncryptUtils() {
    throw new IllegalStateException("EncryptUtils");
  }

  private static DESKeySpec getDesKeySpec(String data, String key) throws Exception {
    if (data == null || data.length() == 0) {
      return null;
    }

    cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    byte[] desKey = key.getBytes(StandardCharsets.UTF_8);

    return new DESKeySpec(desKey);
  }

  public static String desEncrypt(String data, String key) throws Exception {

    DESKeySpec desKeySpec = getDesKeySpec(data, key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    IvParameterSpec desIV = new IvParameterSpec(key.getBytes(StandardCharsets.UTF_8));
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, desIV);
    byte[] pasByte = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

    Base64.Encoder encoder = Base64.getEncoder();

    return encoder.encodeToString(pasByte);
  }

  public static String desDecrypt(String data, String key) throws Exception {

    DESKeySpec desKeySpec = getDesKeySpec(data, key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

    IvParameterSpec desIV = new IvParameterSpec(key.getBytes(StandardCharsets.UTF_8));
    cipher.init(Cipher.DECRYPT_MODE, secretKey, desIV);

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] retBytes = cipher.doFinal(decoder.decode(data));

    return new String(retBytes);
  }
}
